import * as fs from 'fs';
import axios from "axios";
import * as path from "path"

const audioDir = path.join(__dirname, '../../../../public/audio');
if (!fs.existsSync(audioDir)) {
    fs.mkdirSync(audioDir, { recursive: true });
}
/**
 * 生成语音文件并保存到本地
 * @param {string} text - 要转换为语音的文本
 * @param {string} voice - 语音角色，默认为 zh-CN-YunxiaNeural
 * @param {string} speed - 语音速度，默认为 1.0
 * @returns {Promise<string>} - 返回保存的文件路径
 */
export async function generateSpeech(text, voice = 'zh-CN-YunxiaNeural', speed = '1.0') {
    return new Promise(async (resolve) => {
        const data = JSON.stringify({
            voice,
            input: text,
            speed
        });

        const config = {
            method: 'post',
            maxBodyLength: Infinity,
            url: 'http://localhost:7899/v1/audio/speech',
            headers: {
                'Content-Type': 'application/json'
            },
            data,
            responseType: 'arraybuffer' as const,
        };

        try {
            const response = await axios.request(config);
            const timestamp = Date.now();
            const fileName = `speech_${timestamp}.mp3`;
            const filePath = path.join(audioDir, fileName);
            console.log(filePath)
            fs.writeFileSync(filePath, response.data);
            resolve({
                fileName,
                filePath,
                timestamp,
                text,
                voice,
                speed
            })
        } catch (error) {
            resolve({ error })
        }
    })
}
